package com.swgk.core.util;

import android.app.ActivityManager;
import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.EditText;

import com.swgk.core.BaseAppApplication;
import com.swgk.core.BaseAppHelper;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.matches;

public class CheckUtils {

    public static boolean isMobileNum(String phone) {

        if (!TextUtils.isEmpty(phone) && phone.length() == 11) {
//            Pattern p = Pattern.compile("^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$");
            Pattern p = Pattern.compile("^[1]\\d{10}$");
            Matcher m = p.matcher(phone);
            return m.matches();
        }
        return false;
    }

    //仅支持11位手机号验证规则：13/14/15/16/17/18/19开头+9位数字（手机号）；
    public static boolean isMobileNum_new(String phone) {

        if (!TextUtils.isEmpty(phone) && phone.length() == 11) {
            Pattern p = Pattern.compile("^(13|14|15|16|17|18|19)[0-9]{9}$");
            Matcher m = p.matcher(phone);
            return m.matches();
        }
        return false;
    }

    /* 验证号码 手机号 固话均可
     * */
    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;

        String expression = "((^(13|14|15|17|18|19)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        CharSequence inputStr = phoneNumber;

        Pattern pattern = Pattern.compile(expression);

        Matcher matcher = pattern.matcher(inputStr);

        if (matcher.matches()) {
            isValid = true;
        }

        return isValid;

    }

    public static boolean isPassword(String s) {
        Pattern p = Pattern.compile("^(?=.*?[a-zA-Z0-9])(?=.*?[0-9])[a-zA-Z0-9_]{6,18}$");
        return p.matcher(s).matches();
    }
    //正整数判断
    public static boolean isNumbers(String s) {
        Pattern p = Pattern.compile("^[1-9]\\d*$");
        return p.matcher(s).matches();
    }

    public static boolean isNumber(String string) {
        if (string == null)
            return false;
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(string).matches();
    }

    public static boolean isLegalName(String name) {
        if (name.contains("·") || name.contains("•")) {
            if (name.matches("^[\\u4e00-\\u9fa5]+[·•][\\u4e00-\\u9fa5]+$")) {
                return true;
            } else {
                return false;
            }
        } else {
            if (name.matches("^[\\u4e00-\\u9fa5]+$")) {
                return true;
            } else {
                return false;
            }
        }
    }

    public static void setEditFilterName(EditText editText, final int maxLength) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[a-zA-Z|\\u4e00-\\u9fa5]+";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (!matcher.find() || dend >= maxLength) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    public static void setEditFilterWeixin(EditText editText, final int maxLength) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]|[\\u4e00-\\u9fa5]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find() || dend >= maxLength) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    public static void setEditFilterEmoji(EditText editText, final int maxLength) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find() || dend >= maxLength) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    public static void setEditFilterOhter(EditText editText, final int maxLength) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                //特殊字符[`~!@#$%^&*()+=|{}':;',\[\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]
                //emoji [\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]
                String speChat = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]|[`~!@#$%^&*()+=|{}''\\[\\].<>/~@#￥%……&*（）——+|{}【】‘”“’]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find() || dend >= maxLength) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    public static void setEditFilterNumber(EditText editText, final int maxLength) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "^[0-9]*$";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                boolean find = matcher.find();
                if (!find || dend >= maxLength) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    public static boolean isNotEmptyBatch(String... strs) {
        for (String str : strs) {
            if (str == null || "".equals(str.trim()))
                return false;
        }
        return true;
    }

    /*** 验证电话号码
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsTelephone(String str) {
        String regex = "^0(10|2[0-5789]-|\\d{3})-?\\d{7,8}$";
        return matches(regex, str);
    }

    public static String settingphone(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }

    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    //邮箱验证
    public static boolean isEmails(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    public static boolean isMobile(String mobile) {
        return checkMobile(mobile) || checkPhone(mobile);
    }

//    /**
//     * 验证手机号码（支持国际格式，+86135xxxx...（中国内地），+00852137xxxx...（中国香港））
//     *
//     * @param mobile 移动、联通、电信运营商的号码段
//     *               <p>移动的号段：134(0-8)、135、136、137、138、139、147（预计用于TD上网卡）
//     *               、150、151、152、157（TD专用）、158、159、187（未启用）、188（TD专用）</p>
//     *               <p>联通的号段：130、131、132、155、156（世界风专用）、185（未启用）、186（3g）</p>
//     *               <p>电信的号段：133、153、180（未启用）、189</p>
//     * @return 验证成功返回true，验证失败返回false
//     */
//    public static boolean checkMobile(String mobile) {
//        String regex = "^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\\d{8}$";
//        boolean s = Pattern.matches(regex, mobile);
//        return Pattern.matches(regex, mobile);
//    }

    /**
     * 手机号号段校验，
     第1位：1；
     第2位：{3、4、5、6、7、8、9}任意数字；
     第3—11位：0—9任意数字
     * @param value
     * @return
     */
    public static boolean checkMobile(String value) {
        if (value != null && value.length() == 11) {
            Pattern pattern = Pattern.compile("^1[2|3|4|5|6|7|8|9][0-9]\\d{8}$");
            Matcher matcher = pattern.matcher(value);
            return matcher.matches();
        }
        return false;
    }

    /**
     * 验证固定电话号码
     *
     * @param phone 电话号码，格式：国家（地区）电话代码 + 区号（城市代码） + 电话号码，如：+8602085588447
     *              <p><b>国家（地区） 代码 ：</b>标识电话号码的国家（地区）的标准国家（地区）代码。它包含从 0 到 9 的一位或多位数字，
     *              数字之后是空格分隔的国家（地区）代码。</p>
     *              <p><b>区号（城市代码）：</b>这可能包含一个或多个从 0 到 9 的数字，地区或城市代码放在圆括号——
     *              对不使用地区或城市代码的国家（地区），则省略该组件。</p>
     *              <p><b>电话号码：</b>这包含从 0 到 9 的一个或多个数字 </p>
     * @return 验证成功返回true，验证失败返回false
     */
    public static boolean checkPhone(String phone) {
        String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
        boolean s = Pattern.matches(regex, phone);
        return Pattern.matches(regex, phone);
    }

    /**
     * 判断服务是否启动,context上下文对象 ，className服务的name
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        if (mContext == null){
            mContext = BaseAppHelper.get().getInstance();
        }
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);

        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().contains(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    //身份证效验
    public static boolean isIDNumber(String IDNumber) {
        if (!TextUtils.isEmpty(IDNumber)){
            String reg = "^\\d{15}$|^\\d{17}[0-9Xx]$";
            if (!IDNumber.matches(reg)) {
                return false;
            }
            return true;
        }else {
            return false;
        }
    }

    //身份证效验
    public static boolean isVersionTwoIDNumber(String IDNumber) {
        if (!TextUtils.isEmpty(IDNumber)){
            String reg = "^\\d{17}[0-9Xx]$";
            if (!IDNumber.matches(reg)) {
                return false;
            }
            return true;
        }else {
            return false;
        }
    }

    //驾驶证档案编号
    public static boolean isDriveFileNumber(String number) {
        if (!TextUtils.isEmpty(number)){
            return number.length()==12;
        }else {
            return false;
        }
    }

    /**
     * 按企业服务1.0.7需求
     * @param mobile
     * @return
     */
    public static boolean isMobileForService(String mobile) {
        return checkMobileForService(mobile) || checkPhoneForService(mobile);
    }

    /**
     * 按企业服务1.0.7需求
     * 验证手机号码（支持国际格式，+86135xxxx...（中国内地），+00852137xxxx...（中国香港））
     * 13/14/15/16/17/18/19开头+9位数字
     * @return 验证成功返回true，验证失败返回false
     */
    public static boolean checkMobileForService(String mobile) {
        String regex = "^1([3-9])\\d{9}$";
        boolean s = Pattern.matches(regex, mobile);
        return Pattern.matches(regex, mobile);
    }

    /**
     * 按企业服务1.0.7需求
     * 验证固定电话号码
     *
     * @param phone 前面是0开头，后面跟着2-3位数字，“-”后面是7-8位数字。“-”可省略
     * @return 验证成功返回true，验证失败返回false
     */
    public static boolean checkPhoneForService(String phone) {
        String regex = "^0(\\d{2,3}\\-?)?\\d{7,8}$";
        boolean s = Pattern.matches(regex, phone);
        return Pattern.matches(regex, phone);
    }

}
